package com.we823.project.repository.service.we;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.we823.project.model.we.ResourceModel;
import com.we823.project.repository.dao.we.ResourceRepository;
import com.we823.project.repository.service.AbstractBaseService;

@Service("resourceService")
@Scope("prototype")
public class ResourceService extends AbstractBaseService<ResourceModel> {

	private ResourceRepository resourceRepository;
	
	@Autowired
	public ResourceService(ResourceRepository resourceRepository) {
		super(resourceRepository);
		this.resourceRepository=resourceRepository;
	}

	public List<ResourceModel> findByParentid(int parentid){
		return this.resourceRepository.findByParentid(parentid);
	}

	public List<ResourceModel> getListInMapByParentid(int parentid) {
		Map<Integer, List<ResourceModel>> map = parentMap();
		return map.get(parentid);
	}

	public Map<Integer, ResourceModel> map() {
		Map<Integer, ResourceModel> map = new HashMap<Integer, ResourceModel>();
		Sort sort = new Sort(Direction.ASC,"orderid");
		List<ResourceModel> resourceModels = findAll(sort);
		if(resourceModels!=null && resourceModels.size()>0) {
			for (ResourceModel resourceModel : resourceModels) {
				map.put(resourceModel.getId(), resourceModel);
			}
		}
		return map;
	}
	
	public Map<Integer, List<ResourceModel>> parentMap(){
		Map<Integer, List<ResourceModel>> parentMap = new HashMap<>();
		Sort sort = new Sort(Direction.ASC,"orderid");
		List<ResourceModel> resourceModels = findAll(sort);
		if(resourceModels!=null && resourceModels.size()>0) {
			for (ResourceModel resourceModel : resourceModels) {
				int parentid = resourceModel.getParentid();
				List<ResourceModel> resourceList = parentMap.get(parentid);
				if(resourceList==null) {
					resourceList = new ArrayList<>();
					parentMap.put(parentid, resourceList);
				}
				resourceList.add(resourceModel);
			}
			
			for (ResourceModel resourceModel : resourceModels) {
				resourceModel.setSubresources(parentMap.get(resourceModel.getId()));
			}
		}
		return parentMap;
	}
}
